import { createI18n } from 'vue-i18n'
import { messages } from './messages'
import { lStorage } from '@/utils/storage'

// 共享配置
const SHARED_DATE_SHORT = {
	year: 'numeric',
	month: 'short',
	day: 'numeric',
}

// 获取浏览器语言（兼容性处理）
const getBrowserLanguage = () => {
	const lang = navigator.language || navigator.userLanguage || 'en'
	return /^zh(-cn|-hans)?$/i.test(lang) ? 'zh' : 'en'
}

// 安全获取存储语言
const getSavedLanguage = () => {
	try {
		return lStorage.get('language') || getBrowserLanguage()
	} catch (e) {
		return getBrowserLanguage()
	}
}

// 创建实例
export const i18n = createI18n({
	legacy: false,
	locale: getSavedLanguage() || 'en',
	fallbackLocale: 'en',
	messages,
	numberFormats: {
		en: { currency: { style: 'currency', currency: 'USD' } },
		zh: { currency: { style: 'currency', currency: 'CNY' } },
	},
	datetimeFormats: {
		zh: {
			short: SHARED_DATE_SHORT,
			long: {
				year: 'numeric',
				month: 'long',
				day: 'numeric',
				weekday: 'long',
				hour: 'numeric',
				minute: 'numeric',
			},
		},
		en: {
			short: SHARED_DATE_SHORT,
			long: {
				year: 'numeric',
				month: 'long',
				day: 'numeric',
				weekday: 'long',
				hour: 'numeric',
				minute: 'numeric',
				hour12: true,
			},
		},
	},
})
